#pragma once

#include "const.h"
#include <thread>
#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/exception.h>

#include <queue>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <thread>



class SqlConnection
{
public:
	SqlConnection(sql::Connection* con, int64_t lasttime) : m_con(con), m_last_operator_time(lasttime) {

	}

public:
	std::unique_ptr<sql::Connection> m_con;
	int64_t m_last_operator_time; // 最后一次执行Mysql数据库的操作时间
};


class MySqlPool
{
public:
	MySqlPool(const std::string& url, const std::string& user, const std::string& pass, const std::string& schema, int poolSize);
	~MySqlPool();

	// 检测存活连接
	void checkConnection();

	std::unique_ptr<SqlConnection> getConnection();
	void returnConnection(std::unique_ptr<SqlConnection> con);
	void Close();

private:
	std::string m_url;
	std::string m_user;
	std::string m_passwd;
	std::string m_schema; // 数据库名
	int m_poolSize;
	std::queue<std::unique_ptr<SqlConnection>> m_pool;
	std::mutex m_mutex;
	std::condition_variable m_cond;
	std::atomic_bool m_b_stop;
	std::thread m_check_thread; // 检测连接的线程（采用心跳机制）
};

class MysqlDao
{
public:
	MysqlDao();
	~MysqlDao();

	int registerUser(const std::string& name, const std::string& email, const std::string& pwd);
	bool checkEmail(const std::string& name, const std::string& email);
	bool updatePwd(const std::string& name, const std::string& newpwd);
	bool checkPwd(const std::string& name, const std::string& pwd, UserInfo& userInfo);
	std::shared_ptr<UserInfo> getUserInfo(int uid);

private:
	std::unique_ptr<MySqlPool> m_pool;
	std::mutex m_mutex;
};

